package com.lmx.repoDomain.repository;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.CommonService;
import com.lmx.persistence.service.CustomerService;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.tmodel.ServiceFinishLevel;
import com.lmx.repoDomain.tmodel.ServicesExe;
import com.lmx.repoDomain.tmodel.SpecService;

@JsonApiResourceRepository(ServicesExe.class)
@Component
public class ServicesExeRepository extends BaseRepository<ServicesExe> {

	@Autowired
	private NursingService nursingService;

	@Autowired
	private CommonService commonService;

	@SuppressWarnings("unchecked")
	@Override
	@JsonApiFindAll
	public Iterable<ServicesExe> findAll(final QueryParams requestParams) {
		List<ServicesExe> listData = new ArrayList<>();
		Map<String, String> keyMap = CommonUtil.getKeyMapByFilter(requestParams);
		String customerId = keyMap.get("flagQueryType");
		Integer nowDate = CommonUtil.getCurrTimes();
		Integer curTimeEnd = 0;
		try {
			curTimeEnd= CommonUtil.strToIntegerTime(CommonUtil.getCurrTimeForString().substring(0, 10) + " 23:59:59");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Integer dayBegin = CommonUtil.getDayBegin(new Date());
		Integer endTime = dayBegin - 6 * 24 * 60 * 60;// 六天前零点时间
		listData = nursingService.getServicesExe(endTime, nowDate,Long.parseLong(customerId));
		Map<String, String> flagMap = (Map<String, String>) listData.stream().collect(
				Collectors.toMap(ServicesExe::getDateString, ServicesExe::getDateString, (key1, key2) -> key2));
		//7天数据时间tab
		for (int i = 0; i < 7; i++) {
			ServicesExe exe = new ServicesExe();
			String dateTabString = null;
			Integer dateTab = curTimeEnd - i * 24 * 60 * 60;
			if (i == 0) {
				dateTab = nowDate;
			}
			//判断七天内哪天没有数据
			if(flagMap.containsKey(CommonUtil.integetTimeForString(dateTab).substring(0, 10))){
				
			}else{
				continue;
			}
			exe.setDateTab(new Long(dateTab)); 
			dateTabString = CommonUtil.integetTimeForString(dateTab).substring(0, 10) + " "
					+ CommonUtil.getWeekOfDate(new Date(dateTab * 1000l));
			exe.setDateTabString(dateTabString);
			exe.setId(i + 1l);
			listData.add(exe);
		}
		commonService.setPageInfo(listData, requestParams);
		// 按照时间排序
		Collections.sort(listData);
		listData=commonService.getPageData(listData, requestParams);
		return listData;
	}

}
